package com.team.instantsharing.plugin

import java.nio.charset.Charset;

import uk.co.desirableobjects.oauth.scribe.OauthService;

import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.util.WebUtils;
import org.scribe.model.Token;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.team.instantsharing.dto.LoginResponse;
import com.team.instantsharing.dto.Message;
import com.team.instantsharing.dto.User;
import com.team.instantsharing.ultils.Constant;
import com.team.instantsharing.ultils.FileConvert;
import com.team.instantsharing.ultils.RequestHeader;
import com.team.instantsharing.ultils.ServiceRequest;

import groovy.sql.Sql
import grails.converters.JSON;

class PluginController {
	OauthService oauthService

	def signInFacebook() {
		Token facebookAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('facebook')]
		if (facebookAccessToken) {
			def facebookResource = oauthService.getFacebookResource(facebookAccessToken, "https://graph.facebook.com/me")
			def facebookResponse = JSON.parse(facebookResource?.getBody())

			Map data = [id: facebookResponse.id, name: facebookResponse.name, email: facebookResponse.email]
			
			//Register Social
			RestTemplate restTemplate = new RestTemplate();
			HttpEntity entity = new HttpEntity(RequestHeader.getDefaultHeader());
			Message checkEmailMessage = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.CHECK_EMAIL_EXIST + "?userEmail=" + data.get("email"), HttpMethod.GET, entity, Message.class).body;
			if (checkEmailMessage.response.equals("false")) {
				User user = new User();
				user.setUserEmail(data.get("email"));
				user.setUserName(data.get("name"));
				user.setPassword(data.get("id"));
				user.setActivated(true);
		
				RestTemplate restTemplateRegister = new RestTemplate();
				HttpEntity<User> userRegisterEntity = new HttpEntity<User>(user, RequestHeader.getDefaultHeader());
				Message registerResponse = restTemplateRegister.exchange(Constant.SERVICE_URL + ServiceRequest.REGISTER_SOCIAL, HttpMethod.POST, userRegisterEntity, Message.class).body;
			}
			//Login Social
			User userLogin = new User();
			userLogin.setUserEmail(data.get("email"));
			userLogin.setPassword(Constant.SECRET_KEY_SOCIAL);
			RestTemplate restTemplateLogin = new RestTemplate();
			HttpEntity<User> userLoginEntity = new HttpEntity<User>(userLogin, RequestHeader.getDefaultHeader());
			LoginResponse loginResponse = restTemplateLogin.exchange(Constant.SERVICE_URL + ServiceRequest.LOGIN_SOCIAL, HttpMethod.POST, userLoginEntity, LoginResponse.class).body;
			if (loginResponse.getUserId() > 0){
				session.userName = data.get("name");
				session.userPicture = "https://graph.facebook.com/" + data.get("id")+  "/picture";
				session.userId = loginResponse.getUserId();
				session.userToken = loginResponse.getUserToken();
				session.userEmail = data.get("email");
				session.availableCapacity = loginResponse.getAvailableCapacity();
				session.usedCapacity = loginResponse.getUsedCapacity();
				session.availableCapacityString = FileConvert.getDocumentCapacityString(loginResponse.getAvailableCapacity());
				session.usedCapacityString = FileConvert.getDocumentCapacityString(loginResponse.getUsedCapacity());
				redirect controller:'manage', action:'index';
			}
			else{
				redirect controller:'home', action:'index';
			}
		}
	}

	def signInGoogle() {
		Token googleAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('google')]
		if (googleAccessToken) {
			def googleResource = oauthService.getGoogleResource(googleAccessToken, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json")
			def googleResponse = JSON.parse(googleResource?.getBody())

			Map data = [id: googleResponse.id, name: googleResponse.name, email: googleResponse.email, picture: googleResponse.picture]
			
			//Register Social
			RestTemplate restTemplate = new RestTemplate();
			HttpEntity entity = new HttpEntity(RequestHeader.getDefaultHeader());
			Message checkEmailMessage = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.CHECK_EMAIL_EXIST + "?userEmail=" + data.get("email"), HttpMethod.GET, entity, Message.class).body;
			
			if (checkEmailMessage.response.equals("false")) {
				User user = new User();
				user.setUserEmail(data.get("email"));
				user.setUserName(data.get("name"));
				user.setPassword(data.get("id"));
				user.setActivated(true);
		
				RestTemplate restTemplateRegister = new RestTemplate();
				HttpEntity<User> userRegisterEntity = new HttpEntity<User>(user, RequestHeader.getDefaultHeader());
				Message registerResponse = restTemplateRegister.exchange(Constant.SERVICE_URL + ServiceRequest.REGISTER_SOCIAL, HttpMethod.POST, userRegisterEntity, Message.class).body;
			}
			//Login Social
			User userLogin = new User();
			userLogin.setUserEmail(data.get("email"));
			userLogin.setPassword(Constant.SECRET_KEY_SOCIAL);
			RestTemplate restTemplateLogin = new RestTemplate();
			HttpEntity<User> userLoginEntity = new HttpEntity<User>(userLogin, RequestHeader.getDefaultHeader());
			LoginResponse loginResponse = restTemplateLogin.exchange(Constant.SERVICE_URL + ServiceRequest.LOGIN_SOCIAL, HttpMethod.POST, userLoginEntity, LoginResponse.class).body;
			if (loginResponse.getUserId() > 0){
				session.userName = data.get("name");
				session.userPicture = data.get("picture");
				session.userId = loginResponse.getUserId();
				session.userToken = loginResponse.getUserToken();
				session.userEmail = data.get("email");
				session.availableCapacity = loginResponse.getAvailableCapacity();
				session.usedCapacity = loginResponse.getUsedCapacity();
				redirect controller:'manage', action:'index';
			}
			else{
				redirect controller:'home', action:'index';
			}
		}
	}
}
